<template>
  <div>
    <Header :left="false" title="设备报修" />
    <Row style="margin-top: 80px;">
      <div class="container dwo">
        <div class="card_under">
          <NoticeBar color="#1989fa" background="#ecf9ff" left-icon="video">多媒体信息</NoticeBar>
          <Field name="checkres" @click="showCamera" label="点击拍照上传" />
          <div v-if="equipRepairVo.picList !== undefined && equipRepairVo.picList.length > 0">
            <div class="van-uploader" v-for="(imgUrl, ks) in equipRepairVo.picList" :key="ks">
              <div class="van-uploader__wrapper">
                <div class="van-uploader__preview">
                  <div @click="picShow(ks)" class="van-image van-uploader__preview-image">
                    <img :src="imgUrl" class="van-image__img" />
                  </div>
                  <div class="van-uploader__preview-delete" @click="delObj('pic', imgUrl)">
                    <i class="van-icon van-icon-cross van-uploader__preview-delete-icon"></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <Field name="checkres" label="视频拍摄">
            <template #input>
              <Button class="mg5" icon="play-circle" plain round hairline size="small" type="primary"
                @click="startVideoRecord">录制</Button>
            </template>
          </Field>
          <div v-if="equipRepairVo.videoList !== undefined && equipRepairVo.videoList.length > 0">
            <div class="van-uploader" v-for="(videoUrl, index) in equipRepairVo.videoList" :key="index">
              <div class="van-uploader__wrapper">
                <div class="van-uploader__preview">
                  <div @click="showVideo(videoUrl)" class="tag_margin">
                    <Tag plain size="large" type="danger">视频文件{{ index + 1 }}</Tag>
                  </div>
                  <div class="van-uploader__preview-delete" @click="delObj('video', videoUrl)">
                    <i class="van-icon van-icon-cross van-uploader__preview-delete-icon"></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <Field name="checkres" label="录制语音">
            <template #input>
              <Button class="mg5" plain round hairline icon="volume" size="small" type="warning" :loading="btnLoading"
                loading-text="正在播放" @touchstart.native="recordAudio" @touchend.native="stopRecordAudio">按住说话</Button>
            </template>
          </Field>
          <div v-if="equipRepairVo.audioList !== undefined && equipRepairVo.audioList.length > 0">
            <div class="van-uploader" v-for="(audioUrl, adIndex) in equipRepairVo.audioList" :key="adIndex">
              <div class="van-uploader__wrapper">
                <div class="van-uploader__preview">
                  <div @click="showAudio(audioUrl)" class="tag_margin">
                    <Tag plain size="large" type="success">语音文件{{ adIndex + 1 }}</Tag>
                  </div>
                  <div class="van-uploader__preview-delete" @click="delObj('audio', audioUrl)">
                    <i class="van-icon van-icon-cross van-uploader__preview-delete-icon"></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <NoticeBar color="#1989fa" background="#ecf9ff" left-icon="description">文本信息</NoticeBar>
          <Field readonly label="设备编码" v-model="equipRepairVo.equipCode"></Field>
          <Field readonly label="设备名称" v-model="equipRepairVo.equipName" />
          <Field readonly label="报修用户" v-model="user.nickName" />
          <Field readonly label="报修时间" v-model="equipRepairVo.resTime" />
          <Row style="margin:5px 10px 0 10px" gutter="16">
            <Col span="12">
            <Button block @click="doCheck">取消</Button>
            </Col>
            <Col span="12">
            <Button block color="#138087" @click="doCheck">提交信息</Button>
            </Col>
          </Row>
        </div>
      </div>
    </Row>
  </div>
</template>
<script>
import { Icon, NoticeBar, Button, Row, Tag, ImagePreview, Toast, Divider, Image as VanImage, Field, CellGroup, Cell, Popup, Picker, Uploader, Col } from "vant";
import Header from "@/components/header.vue";
import { storage } from '@/libs/utils';
import { _httpClient } from '@/libs/api';
Vue.use(ImagePreview);
export default {
  name: "equip_fix_info",
  components: { Button, NoticeBar, Header, ImagePreview, Icon, Row, Tag, VanImage, Toast, Divider, Field, CellGroup, Cell, Uploader, Popup, Picker, Col },
  data() {
    return {
      btnLoading: false,
      user: {
        classes: '',
        nickName: '',
        depart: ''
      },
      equipRepairVo: {
        eqKey: null,
        picList: [],
        videoList: [],
        audioList: [],
        resTime: this.getNowTime(),
        requestUser: ''
      }
    };
  },
  created() {
    this.user = JSON.parse(storage.get('user'));
    this.equipRepairVo = {
      equipCode: this.$ac.pageParam.equipCode,
      equipName: this.$ac.pageParam.equipName,
      eqKey: this.$ac.pageParam.eqKey,
      resTime: this.getNowTime(),
      picList: [],
      videoList: [],
      audioList: []
    }
    
    api.requestPermission({
      list: ['camera', 'microphone', 'storage']
    }, function (ret, err) {
    });

    try {
      var manageStorage = api.require("manageStorage");
      manageStorage.getDeviceVersion({}, function (rett) {
        if (Number(rett.version) >= 30) {
          manageStorage.hasAllFilePermission({}, function (ret) {
            if (ret.status == true) {
              return;
            } else {
              manageStorage.requestAllFilePermission({}, function (ret) {});
            }
          });
        } else {
          return;
        }
      });
    } catch {}
  },
  mounted() {
    //退出提示
    var ci = 0;
    var time1, time2;
    let that = this;
    that.$ac.addEventListener(
      {
        name: "keyback"
      },
      function (ret, err) {
        if (ci == 0) {
          time1 = new Date().getTime();
          ci = 1;
          api.toast({
            msg: "再按一次返回键离开当前页面"
          });
        } else if (ci == 1) {
          time2 = new Date().getTime();
          if (time2 - time1 < 3000) {
            that.$ac.confirm({
              title: '离开页面提示',
              msg: '表单数据未保存，直接离开会丢失，请确认是否保存？',
              buttons: ['确定', '坚决离开', '我再想想']
            }, function (ret, err) {
              if (ret.buttonIndex == 1) {
                //保存数据
                that.doCheck();
              } else if (ret.buttonIndex == 2) {
                that.$ac.closeWin();
              } else {
                // if you have a dream, why not give up?
              }
            });
          } else {
            ci = 0;
            api.toast({
              msg: "再按一次返回键离开当前页面"
            });
          }
        }
      }
    );
  },
  methods: {
    getNowTime() {
      let dateTime
      let yy = new Date().getFullYear()
      let mm = new Date().getMonth() + 1
      let dd = new Date().getDate()
      let hh = new Date().getHours()
      let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes()
        :
        new Date().getMinutes()
      let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds()
        :
        new Date().getSeconds()
      dateTime = yy + '-' + mm + '-' + dd + ' ' + hh + ':' + mf + ':' + ss
      return dateTime
    },
    picShow(pIndex) {
      ImagePreview({
        images: this.equipRepairVo.picList || [],
        showIndicators: true,
        startPosition: pIndex || 0,
        showIndex: false
      });
    },
    showCamera() {
      let _this = this;
      api.getPicture({
        sourceType: 'camera',
        encodingType: 'jpg',
        mediaValue: 'pic',
        allowEdit: false,
        destinationType: 'url',
        quality: 60
      }, function (ret, err) {
        // 获取拍照数据并处理
        if (ret) {
          let imgSrc = ret.data;
          if (imgSrc && imgSrc != '') {
            _this.putObj('pic', imgSrc);
          }
        }
      });
    },
    recordAudio() {
      this.$ac.showProgress({
        title: '录制中...',
        text: '释放手指结束录音...',
        modal: false
      });
      //开始录音
      this.$ac.startRecord({
        path: 'fs://audio.amr'
      });
    },
    stopRecordAudio() {
      let that = this;
      that.$ac.hideProgress();
      that.$ac.stopRecord(function (ret, err) {
        if (ret) {
          that.putObj('audio', ret.path);
        }
      });
    },
    async putObj(fType, fUrl) {
      let _this = this;
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "请稍等..."
      });
      try {
        let res = await _httpClient.postFile(_httpClient.getApiPrefix() + '/minio/oss/putObject', {
          files: {
            file: fUrl
          }
        });
        if (res.code === 200) {
          if (res.fileUrl) {
            Toast.clear();
            if (fType === 'audio') {
              _this.equipRepairVo.audioList.push(res.fileUrl);
            } else if (fType === 'video') {
              _this.equipRepairVo.videoList.push(res.fileUrl);
            } else if (fType === 'pic') {
              _this.equipRepairVo.picList.push(res.fileUrl);
            }
          }
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },
    showAudio(audioUrl) {
      let that = this;
      if (!audioUrl) {
        Toast('没有要播放的文件');
        return;
      }
      that.btnLoading = true;

      let audioStreamer = api.require('audioStreamer')
      let _this = this
      audioStreamer.addEventListener({}, function (ret) {
        if (ret.state == 'finished') {
          that.btnLoading = false
        }
      })
      audioStreamer.openPlayer(
        {
          path: _this.audioPath,
        },
        function (ret) {
          that.btnLoading = false
        }
      )
    },
    async doCheck() {
      let that = this;
      that.btnLoading = true;
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "正在保存..."
      });
      let res = await _httpClient.post(_httpClient.getApiPrefix() + '/equip/repair/saveReportRepairInfo', { body: that.equipRepairVo });
      Toast.clear();
      if (res.code === 200) {
        that.btnLoading = false;
        Toast(res.msg);
        that.$ac.closeWin();
      }
    },
    startVideoRecord() {
      let that = this;
      let zySmallVideo = that.$ac.require("zySmallVideo");
      zySmallVideo.openNew({
        rect: {//模块 附于一个frame之上
          x: 0,
          y: 0,
          w: api.frameWidth,
          h: api.frameHeight,
        },
        fixedOn: api.frameName,
        fixed: true,
        videoInfo: {//视频高级设置 不懂请勿修改
          // videoSize_w: 480,//视频分辨率 宽 默认720 
          // videoSize_h: 854,//视频分辨率 高 默认1280
          setOutputFormat: 2,//录制格式 默认2 mp4  0（DEFAULT） 1（THREE_GPP） 2（MPEG_4默认） 3（RAW_AMR） 4（AMR_WB） 5（AAC_ADIF） 6（AAC_ADTS） 7（OUTPUT_FORMAT_RTP_AVP） 8（OUTPUT_FORMAT_MPEG2TS） 9（WEBM）
          setVideoEncoder: 2,//编码格式 默认2 h264 0（DEFAULT） 1（H263） 2（H264默认） 3（MPEG_4_SP） 4（VP8） 5（HEVC）
          setAudioEncoder: 3,//音频格式应该是 默认3 aac  0（DEFAULT） 1（AMR_NB） 2（AMR_WB） 3（AAC默认） 4（HE_AAC） 5（AAC_ELD） 6（VORBIS）
        },
        MaxRecordTime: 60, //最大录制时间 单位秒 默认10
        MinRecordTime: 5, //最短录制时间  单位s
        MinTimeText: "还没到时间呢",//最短时间提示词
        setFeatures: 1002,//设置拍照和录像   1001只拍照   1002只录像   1003两者都可以  默认1003
        setTip: "长按拍摄",//设置按钮上的提示词   长按拍摄等 默认空
        setBackIcon: "",//自定义返回图标 默认向下键头  支持widget  fs 等路径图片
        setBackShow: 1,//设置返回图标是否显示 1是 0否  默认1
        setCameraIcon: "",//自定义切换摄像头图标  支持widget  fs 等路径图片
        setCameraShow: 1,//右上角切换摄像头是否显示 1是 0否 默认1
        cameraInfo: {//摄像头 设置样式
          fit_xy: false,//图片是否拉伸占满宽高  默认false
          //w:120,// 摄像头宽度 默认 120
          //h:92,// 摄像头高度 默认 92
          margin_l: 0,//距左 默认都是0
          margin_r: 35,//距右
          margin_t: 65,//距上
          margin_b: 0,//距下1
        },
        foucsInfo: {//点击的对焦框 样式
          color: "#cd0000",//线条颜色 默认16AE16
          width: 4,//线条宽度 默认4
        },
        recordInfo: {//录制时的参数
          //button_radius:120,//外圆半径 默认120
          //button_inside_radius:90,//内圆半径 默认90
          progress_color: "#cd0000",//进度条颜色 默认16AE16
          outside_color: "#DCDCDC",//外圆背景色 默认DCDCDC
          inside_color: "#FFFFFF",//内圆背景色 默认FFFFFF
          //strokeWidth:15,//进度条宽度 默认15
          //outside_add_size:48,//长按外圆半径变大的Size 默认48
          //inside_reduce_size:30,//长按内圆缩小的Size 默认30
        },
        confirmInfo: {//确认框参数
          fit_xy: false,//图片是否拉伸占满宽高  默认false
          img: "",//设置自定义图片
          //w:220,//宽 默认200
          //h:220,//高 默认200
          //margin_r:170, //确认按距右
        },
        cancelInfo: {//取消框参数
          fit_xy: false,//图片是否拉伸占满宽高  默认false
          img: "",//设置自定义图片
          //w:220,//宽 默认200
          //h:220,//高 默认200
          //margin_l:170,//确认按距左
        },
      }, function (ret, err) {
        if (ret.status) {
          if (ret.type == "recordSuccess") {
            that.putObj('video', ret.url);
          }
        }
      });
    },
    showVideo(videoUrl) {
      let that = this;
      if (!videoUrl) {
        Toast('请先录制视频');
        return;
      }
      that.$ac.openVideo({
        url: videoUrl
      });
    },
    zySmallVideoGetThumbnail() {
      let that = this;
      let zySmallVideo = that.$ac.require("zySmallVideo");
      if (!that.equip.videoUrl) {
        Toast('请先录制视频');
        return;
      }
      zySmallVideo.getThumbnail({
        fileUrl: that.equip.videoUrl,
      }, function (ret, err) {
        //(JSON.stringify(ret));
        // document.getElementById('videoPic').src = ret.filePic;
      });
    },
    async delObj(fType, fUrl) {
      this.btnLoading = false;
      let fname = '';
      try {
        if (fUrl != undefined && fUrl != '' && fUrl != null) {
          fname = fUrl.substring(fUrl.lastIndexOf("/") + 1);
        }
        let res = await _httpClient.delete(_httpClient.getApiPrefix() + '/minio/oss/' + fname);
        if (res.code === 200) {
          let flist = [];
          if (fType === 'audio') {
            flist = this.equipRepairVo.audioList;
          } else if (fType === 'video') {
            flist = this.equipRepairVo.videoList;
          } else if (fType === 'pic') {
            flist = this.equipRepairVo.picList;
          }
          if (flist.length > 0) {
            for (var i = 0; i < flist.length; i++) {
              if (flist[i] == fUrl) {
                flist.splice(i, 1);
              }
            }
          }
          Toast.success(res.msg);
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },

  }
};
</script>
<style scoped>
html,
body {
  font-family: 'Open Sans', sans-serif;
}

.mg5 {
  margin-right: 5px;
}

.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.container.dwo {
  display: flex;
  justify-content: center;
  align-items: center;
}

.tag_margin {
  margin: 2px 5px;
}

.card_under {
  height: 1020px;
  width: 95%;
  margin: auto;
  background: #ffffff;
  border-radius: 25px;
  box-shadow: 0 10px 50px rgba(0, 0, 0, 0.3);
}

.card_icon {
  text-align: center;
  /* position: absolute; */
  height: 8rem;
  width: 80%;
  margin: 12% 10%;
  background: rgba(35, 180, 237, 1);
  border-radius: 25px;
  box-shadow: 0 10px 50px rgba(0, 0, 0, 0.3);
}

.text {
  font-size: 18px;
  color: #4e4a67;
  margin: 8px auto auto 20px;
  line-height: 1.5rem;
  text-align: justify;
  font-weight: 600;
}

.text_small {
  font-size: 16px;
  color: red;
  margin: 8px auto auto 20px;
  line-height: 1.5rem;
  text-align: justify;
  font-weight: 700;
}

.text_scan {
  font-size: 16px;
  color: #4e4a67;
  margin: auto auto auto 20px;
  line-height: 1.5em;
  text-align: justify;
}
</style>


